using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using sbMembership.Library.Domain;
using sbMembership.Library.Presenters.ViewInterfaces;

namespace sbMembership.Library.Presenters
{
    public class AssignRoleEventArgs : EventArgs
    {
        private string userName;

        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }
    }

    public class AssignRolesToUserPresenter
    {
        private IAssignRolesToUserView  view;
        public enum ActionEnum
        {
           added
           , deleted
           , none
        }

        public AssignRolesToUserPresenter(IAssignRolesToUserView view)
        {
            if (view == null) throw new ArgumentNullException("view may not be null");
            this.view = view;
        }

        public EventHandler AssignRoleCompleteEvent;

        public void InitViewFor(string userName)
        {
            DisplayMessageFor(ActionEnum.none);
            view.AvailableRoles = Roles.GetAllRoles();
            view.UserToAssign = userName;
            view.AssignedRoles = Roles.GetRolesForUser(view.UserToAssign);
        }

        private void DisplayMessageFor(ActionEnum action)
        {
            if (action == ActionEnum.added)
                view.Message = "The role was successfully assigned.";
            else if (action == ActionEnum.deleted)
                view.Message = "The role was successfully removed.";
            else
                view.Message = "Use this form to add a new role.";
        }

        public void AssignRole(string roleName)
        {
            Roles.AddUserToRole(view.UserToAssign, roleName);
            DisplayMessageFor(ActionEnum.added);
            view.AssignedRoles = Roles.GetRolesForUser(view.UserToAssign);
            AssignRoleCompleteEvent(this, null);
        }

        public void RemoveRole(string roleName)
        {
            Roles.RemoveUserFromRole(view.UserToAssign, roleName);
            DisplayMessageFor(ActionEnum.deleted);
            view.AssignedRoles = Roles.GetRolesForUser(view.UserToAssign);
            AssignRoleCompleteEvent(this, null);
        }
    }
}
